package com.example.roam.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.roam.ui.activity.BaseApplication;
import com.example.roam.model.gson.CacheWithDuration;
import com.google.gson.Gson;

public class JsonCacheUtil {
    private static JsonCacheUtil jsonCacheUtil;
    private Gson gson;
    private SharedPreferences sharedPreferences ;
    public JsonCacheUtil(){
        gson = new Gson();
        sharedPreferences = BaseApplication.getAppContext().getSharedPreferences("history", Context.MODE_PRIVATE);
    }

    public static JsonCacheUtil getInstance(){
        if( jsonCacheUtil == null ){
            jsonCacheUtil = new JsonCacheUtil();
        }
        return jsonCacheUtil;
    }

    public void saveCacheWithDuration(String key,Object value,long duration ){
        SharedPreferences.Editor edit = sharedPreferences.edit();
        String strValue = gson.toJson(value);
        CacheWithDuration cacheWithDuration = new CacheWithDuration();
        cacheWithDuration.setDuration(duration+System.currentTimeMillis());
        cacheWithDuration.setValue(strValue);
        String cacheWithDurationStr = gson.toJson(cacheWithDuration);
        edit.putString(key,cacheWithDurationStr);
        edit.commit();
    }

    public <T>T getValue(String key,Class<T> clazz){
        String value = sharedPreferences.getString(key, null);
        CacheWithDuration cacheWithDuration = gson.fromJson(value, CacheWithDuration.class);
        if( cacheWithDuration == null || cacheWithDuration.getDuration() - System.currentTimeMillis() <= 0 ){
            return null;
        }
        T t = gson.fromJson(cacheWithDuration.getValue(), clazz);
        return t;
    }

    public void delCache(String key){
        sharedPreferences.edit().remove(key).commit();
    }

}
